package com.dragee.modules.work.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dragee.common.R;
import com.dragee.config.exception.BusinessException;
import com.dragee.modules.sys.entity.LoginUser;
import com.dragee.modules.work.entity.ApplyProjectEntity;
import com.dragee.modules.work.entity.ApplyScoreEntity;
import com.dragee.modules.work.entity.CompetitionOrderEntity;
import com.dragee.modules.work.entity.CompetitionOrderRefereeEntity;
import com.dragee.modules.work.service.*;
import com.dragee.modules.work.vo.SubmitScoreVo;
import com.dragee.utils.LoginUserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * 出场裁判表
 *
 * @author tc
 * @email tc@mail.com
 * @date 2023-05-08 18:45:10
 */
@RestController
@RequestMapping("work/competitionorderreferee")
@Api(tags = "work - 打分")
public class PlayScoreController {

    @Autowired
    private CompetitionOrderRefereeService competitionOrderRefereeService;
    @Autowired
    private CompetitionOrderService competitionOrderService;
    @Autowired
    private ApplyProjectService applyProjectService;
    @Autowired
    private ApplyService applyService;
    @Autowired
    private ApplyScoreService applyScoreService;


    @GetMapping("getApplyProjectsByOrderId")
    @ApiOperation("获取比赛报名项目通过场次id")
    public R getApplyProjectsByOrderId (@RequestParam("orderId") String orderId) {
        List<ApplyProjectEntity> aps = applyProjectService.list(new QueryWrapper<ApplyProjectEntity>()
                .eq("orderId", orderId));
        aps.forEach(a -> applyService.setApplyProject(a));
        return R.ok().put("data", aps);
    }

    @GetMapping("getScoresByApplyProjectId")
    @ApiOperation("获取打分情况通过报名项目id")
    public R getScoresByApplyProjectId (@RequestParam("applyProjectId") String applyProjectId,
                                        @RequestParam("orderId") String orderId) {
        List<ApplyScoreEntity> as = applyScoreService.list(new QueryWrapper<ApplyScoreEntity>()
                .eq("applyProjectId", applyProjectId).eq("orderId", orderId));
        return R.ok().put("data", as);
    }


    @GetMapping("getNowData")
    @ApiOperation("获取进行中的比赛数据")
    public R getData () {
        LoginUser loginUser = LoginUserUtil.getLoginUser();
        loginUser.getUserId();
        CompetitionOrderRefereeEntity referee = competitionOrderRefereeService.getById(loginUser.getUserId());
        String applyProjectIds = referee.getApplyProjectIds();
        List<ApplyProjectEntity> aps = applyService.getApplyProjectByStatus(applyProjectIds, "正在打分");
        if (aps.size() == 0) {
            return R.ok().put("data", null);
        }
        ApplyScoreEntity as = applyScoreService.getOne(new QueryWrapper<ApplyScoreEntity>()
                .eq("refereeId", referee.getId()).eq("applyProjectId", aps.get(0).getId()), false);

        String orderId = as.getOrderId();
        CompetitionOrderEntity order = competitionOrderService.getById(orderId);
        JSONObject jo = JSONUtil.createObj();
        jo.set("applyProject", aps.get(0));
        jo.set("refereeScore", as);
        jo.set("formula", order.getFormula());
        return R.ok().put("data", jo);
    }

    @GetMapping("getAllData")
    @ApiOperation("获取所有的裁判打分情况和比赛项目的情况")
    public R getAllData () {
        CompetitionOrderRefereeEntity referee
                = competitionOrderRefereeService.getById(LoginUserUtil.getLoginUserId());
        List<ApplyProjectEntity> aps = applyService.getApplyProjectByStatus(referee.getApplyProjectIds(), null);
        for (ApplyProjectEntity ap : aps) {
            if ("打分结束".equals(ap.getStatus())) {
                ApplyScoreEntity as = applyScoreService.getOne(new QueryWrapper<ApplyScoreEntity>().select("score")
                        .eq("type", "裁判长")
                        .eq("applyProjectId", ap.getId())
                        .eq("orderId", ap.getOrderId()), false);
                if (as != null) {
                    ap.setScore(as.getScore());
                }
            }
        }
        JSONObject jo = JSONUtil.createObj();
        jo.set("applyProjects", aps);

        String orderId = aps.get(0).getOrderId();
        List<ApplyScoreEntity> as = new ArrayList<>();
        ApplyProjectEntity nowAP = applyProjectService.getOne(new QueryWrapper<ApplyProjectEntity>()
                .eq("orderId", orderId).eq("status", "正在打分"), false);
        if (nowAP != null) {
            as = applyScoreService.list(new QueryWrapper<ApplyScoreEntity>()
                    .eq("orderId", orderId)
                    .eq("applyProjectId", nowAP.getId()));
        }
        jo.set("refereeScore", as);
        return R.ok().put("data", jo);
    }




    @GetMapping("startOrder")
    @ApiOperation("场次开始比赛")
    public R startOrder (@RequestParam("orderId") Long orderId) {
        CompetitionOrderEntity order = competitionOrderService.getById(orderId);
        order.setStatus("进行中");
        competitionOrderService.saveOrUpdate(order);

        // 设置裁判登录表
        List<CompetitionOrderRefereeEntity> orderReferees = competitionOrderRefereeService
                .list(new QueryWrapper<CompetitionOrderRefereeEntity>()
                        .eq("orderId", orderId));
        for (CompetitionOrderRefereeEntity orderReferee : orderReferees) {
            orderReferee.setLoginStatus("1");
            competitionOrderRefereeService.saveOrUpdate(orderReferee);
        }
        return R.ok();
    }


    @GetMapping("endOrder")
    @ApiOperation("场次结束比赛")
    public R endOrder (@RequestParam("orderId") Long orderId) {
        CompetitionOrderEntity order = competitionOrderService.getById(orderId);
        order.setStatus("已结束");
        competitionOrderService.saveOrUpdate(order);

        // 设置裁判登录表
        List<CompetitionOrderRefereeEntity> orderReferees = competitionOrderRefereeService
                .list(new QueryWrapper<CompetitionOrderRefereeEntity>()
                        .eq("orderId", orderId));
        for (CompetitionOrderRefereeEntity orderReferee : orderReferees) {
            orderReferee.setLoginStatus("0");
            competitionOrderRefereeService.saveOrUpdate(orderReferee);
        }
        return R.ok();
    }



    @GetMapping("startScore")
    @ApiOperation("开始打分")
    public R startScore (@RequestParam("applyProjectId") Long applyProjectId,
                         @RequestParam("orderId") Long orderId) {
        CompetitionOrderEntity order = competitionOrderService.getById(orderId);
        String[] applyProjectIds = order.getApplyProjectIds().split(",");
        int count = applyProjectService.count(new QueryWrapper<ApplyProjectEntity>()
                .in("id", applyProjectIds)
                .eq("status", "正在打分"));
        if (count > 0) {
            throw new BusinessException("请先结束上一场打分");
        }
        ApplyProjectEntity applyProject = applyProjectService.getById(applyProjectId);
        applyProject.setStatus("正在打分");
        applyProjectService.saveOrUpdate(applyProject);

        // 清空表防止重复数据
        applyScoreService.remove(new QueryWrapper<ApplyScoreEntity>()
                .eq("orderId", orderId)
                .eq("applyProjectId", applyProjectId));
        // 增加打分数据
        List<CompetitionOrderRefereeEntity> referees = competitionOrderRefereeService
                .list(new QueryWrapper<CompetitionOrderRefereeEntity>()
                        .eq("orderId", orderId));
        for (CompetitionOrderRefereeEntity referee : referees) {
            ApplyScoreEntity as = new ApplyScoreEntity();
            as.setOrderId(orderId + "");
            as.setApplyProjectId(applyProjectId + "");
            as.setCompetitionId(order.getCompetitionId());
            as.setRefereeId(referee.getId() + "");
            as.setIdCard(referee.getIdCard());
            as.setName(referee.getName());
            as.setType(referee.getType());
            as.setScore(new BigDecimal(0));
            applyScoreService.save(as);
        }
        return R.ok();
    }

    @GetMapping("reStartScore")
    @ApiOperation("管理端修改打分")
    public R reStartScore (@RequestParam("applyProjectId") Long applyProjectId,
                         @RequestParam("orderId") Long orderId) {
        CompetitionOrderEntity order = competitionOrderService.getById(orderId);
        String[] applyProjectIds = order.getApplyProjectIds().split(",");
        int count = applyProjectService.count(new QueryWrapper<ApplyProjectEntity>()
                .in("id", applyProjectIds)
                .eq("status", "正在打分"));
        if (count > 0) {
            throw new BusinessException("请先结束上一场打分");
        }
        ApplyProjectEntity applyProject = applyProjectService.getById(applyProjectId);
        applyProject.setStatus("正在打分");
        applyProjectService.saveOrUpdate(applyProject);
        return R.ok();
    }

    @GetMapping("abstention")
    @ApiOperation("弃权出场")
    public R abstention (@RequestParam("applyProjectId") Long applyProjectId) {
        ApplyProjectEntity applyProject = applyProjectService.getById(applyProjectId);
        applyProject.setStatus("弃权");
        applyProjectService.saveOrUpdate(applyProject);
        return R.ok();
    }

    @GetMapping("endScore")
    @ApiOperation("结束打分")
    public R endScore (@RequestParam("applyProjectId") Long applyProjectId) {
        ApplyProjectEntity applyProject = applyProjectService.getById(applyProjectId);
        applyProject.setStatus("打分结束");
        applyProjectService.saveOrUpdate(applyProject);
        return R.ok();
    }

    @PostMapping("submitScore")
    @ApiOperation("提交打分")
    public R submitScore (@RequestBody SubmitScoreVo vo ) {
        ApplyScoreEntity as = applyScoreService.getOne(new QueryWrapper<ApplyScoreEntity>()
                .eq("orderId", vo.getOrderId())
                .eq("applyProjectId", vo.getApplyProjectId())
                .eq("name", vo.getName())
                .eq("type", vo.getType())
                .eq("idCard", vo.getIdCard()), false);
        if (as == null) {
            throw new BusinessException("请等待管理员开始打分");
        }
        as.setScore(vo.getScore() == null ? BigDecimal.ZERO : vo.getScore());
        as.setSubScore(vo.getSubScore() == null ? BigDecimal.ZERO : vo.getSubScore());
        as.setAddScore(vo.getAddScore() == null ? BigDecimal.ZERO : vo.getAddScore());
        as.setReduceScore(vo.getReduceScore() == null ? BigDecimal.ZERO : vo.getReduceScore());
        as.setAverageScore(vo.getAverageScore() == null ? BigDecimal.ZERO : vo.getAverageScore());
        as.setSightScore(vo.getSightScore() == null ? BigDecimal.ZERO : vo.getSightScore());
        as.setStatus("已打分");
        applyScoreService.saveOrUpdate(as);
        return R.ok();
    }

    @GetMapping("applyUpdateScore")
    @ApiOperation("申请改分")
    public R applyUpdateScore (@RequestParam("refereeId") String refereeId,
                               @RequestParam("applyProjectId") String applyProjectId ) {
        ApplyScoreEntity as = applyScoreService.getOne(new QueryWrapper<ApplyScoreEntity>()
                .eq("refereeId", refereeId).eq("applyProjectId", applyProjectId), false);
        as.setStatus("申请改分待审批");
        applyScoreService.saveOrUpdate(as);
        return R.ok();
    }
    @GetMapping("approveUpdateScore")
    @ApiOperation("审批改分")
    public R approveUpdateScore (@RequestParam("refereeId") String refereeId,
                               @RequestParam("applyProjectId") String applyProjectId,
                                 @RequestParam("result") String result ) {
        ApplyScoreEntity as = applyScoreService.getOne(new QueryWrapper<ApplyScoreEntity>()
                .eq("refereeId", refereeId).eq("applyProjectId", applyProjectId), false);
        if (result.equals("yes")) {
            as.setStatus("未打分");
        } else if (result.equals("no")) {
            as.setStatus("已打分");
        }
        applyScoreService.saveOrUpdate(as);
        return R.ok();
    }


}
